package com.shinbada.core.persistence;

import com.google.common.collect.Lists;
import com.shinbada.common.tree.TreeLevelUtil;
import com.shinbada.common.utils.Reflections;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.Length;

import java.util.List;

/**
 * 数据Entity类
 *
 * @author initcap
 * @version 2017-05-16
 */
public abstract class TreeEntity<T> extends DataEntity<T> {

    private static final long serialVersionUID = 1L;

    /**
     * 父级编号
     */
    protected T parent;
    /**
     * 所有父级编号
     */
    protected String parentIds;
    /**
     * 名称
     */
    protected String name;
    /**
     * 层级名称
     */
    protected String levelName;
    /**
     * 排序
     */
    protected Integer sort;
    /**
     * 父级菜单
     */
    private List<T> children;

    public TreeEntity() {
        super();
        this.sort = 30;
    }

    public TreeEntity(String id) {
        super(id);
    }

    public void add(T node) {
        if (CollectionUtils.isEmpty(children)) {
            children = Lists.newArrayList();
        }
        children.add(node);
    }

    /**
     * 父对象，只能通过子类实现，父类实现mybatis无法读取
     *
     * @return
     */
    public abstract T getParent();

    /**
     * 父对象，只能通过子类实现，父类实现mybatis无法读取
     *
     * @return
     */
    public abstract void setParent(T parent);

    @Length(min = 1, max = 2000)
    public String getParentIds() {
        return parentIds;
    }

    public void setParentIds(String parentIds) {
        this.parentIds = parentIds;
    }

    @Length(min = 1, max = 100)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getSort() {
        return sort;
    }

    public void setSort(Integer sort) {
        this.sort = sort;
    }


    public String getParentId() {
        String id = null;
        if (parent != null) {
            id = (String) Reflections.getFieldValue(parent, "id");
        }
        return StringUtils.isNotBlank(id) ? id : TreeLevelUtil.ROOT;
    }


    public List<T> getChildren() {
        return children;
    }

    public void setChildren(List<T> children) {
        this.children = children;
    }

    public String getLevelName() {
        return levelName;
    }

    public void setLevelName(String levelName) {
        this.levelName = levelName;
    }
}
